import { useState } from 'react'
import { Tree, Menu, message, Input, Modal } from 'antd'
import { DownOutlined, FolderOpenFilled, FolderFilled } from '@ant-design/icons'
import {sortFileTree} from '@/utils/files'
import XmlIcon from './xmlIcon'
import styles from './index.less'

const { DirectoryTree } = Tree

// 自定义的文件夹树形组件
const FileTree = (props) => {
  const [isShowRightMenu, showRightMenu] = useState(false)
  const [isShowAddModal, showAddModal] = useState(false)
  const [isAddDir, setIsAddDir] = useState(false)
  const [currentRightNode, setCurrentRightNode] = useState(null)
  const [newName, setNewName] = useState('')
  const [mousePos, setMousePos] = useState({ x: 0, y: 0 })
  const { dataSource, onSelectXml, currentNode, onRefreshTree } = props

  const onSelect = (keys, info) => {
    if (info.node.isLeaf) {
      onSelectXml(info.node)
    }
  }

  const onExpand = () => {
    console.log('Trigger Expand')
  }

  /**
   * 创建文件夹或文件
   */
  const handleCreate = async (e) => {
    const value = newName.trim()
    // 文件夹名为空
    if (!value) {
      return
    }
    if (isAddDir) {
      if(currentRightNode.children.some(l=>l.title===value)){
        message.error('已存在同名文件夹，不可添加')
        return 
      }
      const newDirectoryHandle = await currentRightNode.handle.getDirectoryHandle(value, {
        create: true
      })
      currentRightNode.children.push({
        parent: currentRightNode,
        handle: newDirectoryHandle,
        children: [],
        isLeaf: false,
        title: value,
        key: currentRightNode.key + '|' + value
      })
    } else {
      const fileName = `${value}.xml`
      if(currentRightNode.children.some(l=>l.title===fileName)){
        message.error('已存在同名文件，不可添加')
        return 
      }
      const newFileHandle = await currentRightNode.handle.getFileHandle(fileName, {
        create: true
      })
      currentRightNode.children.push({
        parent: currentRightNode,
        handle: newFileHandle,
        isLeaf: true,
        title: fileName,
        key: currentRightNode.key + '|' + fileName
      })
    }
    sortFileTree(currentRightNode.children)
    showAddModal(false)
    onRefreshTree()
  }

  /**
   * 关闭新增面板
   */
  const handleCloseAddModal = () => {
    showAddModal(false)
  }

  // 渲染节点
  const renderTitle = (nodeData) => {
    if (nodeData.isError) {
      return <span className={styles.error} >{nodeData.title}</span>
    }
    return nodeData.title
  }

  /**
   * 打开右键弹出框
   */
  const handleOpenRightMenu = (e) => {
    e.event.stopPropagation()
    if (e.node.handle !== null) {
      showRightMenu(true)
      setCurrentRightNode(e.node)
      setMousePos({
        x: e.event.clientX - 30,
        y: e.event.clientY - 30
      })
    }
  }

  /**
   * 删除当前的右键节点
   */
  const handleDelete = () => {
    const parentDir = currentRightNode.parent
    if (!currentRightNode.parent) {
      message.error('不可删除根目录')
      return
    }
    // 删除文件
    if (currentRightNode.handle.kind === 'file') {
      parentDir.handle.removeEntry(currentRightNode.handle.name);
    } else {// 删除文件夹
      parentDir.handle.removeEntry(currentRightNode.handle.name, { recursive: true });
    }
    // 如果右键删除的文件是当前正在编辑的文件，右侧编辑器初始化为未选择状态
    if (currentRightNode.key === currentNode.key) {
      onSelectXml(null)
    }
    currentRightNode.parent.children = currentRightNode.parent.children.filter(l => l.key !== currentRightNode.key)
    onRefreshTree()
  }

  /**
   * 关闭右键菜单项
   */
  const handleCloseRightMenu = () => {
    showRightMenu(false)
  }

  /**
   * 打开新建文件夹面板
   */
  const handleOpenAddDirModal = () => {
    showAddModal(true)
    setIsAddDir(true)
    setNewName('')
  }

  /**
  * 打开新建文件面板
  */
  const handleOpenAddFileModal = () => {
    showAddModal(true)
    setIsAddDir(false)
    setNewName('')
  }

  /**
   * 更改新文件夹名称
   */
  const handleChangeNewName = (e) => {
    setNewName(e.target.value)
  }

  return <div className={styles.fileTree} onClick={handleCloseRightMenu}>
    <DirectoryTree
      switcherIcon={<DownOutlined />}
      icon={(item) => {
        if (item.isLeaf) {
          return <XmlIcon className={styles.xmlColor} />
        }
        return item.expanded ? <FolderOpenFilled className={styles.folderColor} /> : <FolderFilled className={styles.folderColor} />
      }}
      titleRender={renderTitle}
      multiple
      showLine
      defaultExpandAll
      onSelect={onSelect}
      onExpand={onExpand}
      onRightClick={handleOpenRightMenu}
      treeData={dataSource}
    />
    {
      isShowRightMenu && <Menu className={styles.rightMenu} style={{ left: mousePos.x, top: mousePos.y }}>
        {
          currentRightNode.handle.kind === 'directory' && <>
            <Menu.Item key="0" onClick={handleOpenAddFileModal}>新建文件</Menu.Item>
            <Menu.Item key="1" onClick={handleOpenAddDirModal}>新建文件夹</Menu.Item>
            <Menu.Divider />
          </>
        }
        <Menu.Item key="4" onClick={handleDelete}>
          删除
        </Menu.Item>
      </Menu>
    }
    {
      isShowAddModal && <Modal
      okText="确认"
      cancelText="取消"
      visible 
      title={isAddDir ? '新建文件夹' : '新建xml文件'} 
      onOk={handleCreate} onCancel={handleCloseAddModal}
      >
        <Input value={newName} onChange={handleChangeNewName} placeholder={isAddDir ? '请输入文件夹名' : '请输入文件名'} />
      </Modal>
    }
  </div >
}

export default FileTree
